'use client';

import { useEffect, useRef, useState } from 'react';
import { PlayInfo } from '@/lib/utils/types';
import { getEpisodeHistory } from '@/lib/utils/episode-history';

interface HistoryListenerProps {
  playList: PlayInfo[];
}

export default function HistoryListener({ playList }: HistoryListenerProps) {
  // 跟踪是否已初始化历史状态
  const historyInitialized = useRef(false);
  
  useEffect(() => {
    // 在组件挂载时记录当前路径到history栈
    const initialPath = window.location.pathname;
    console.log('初始化历史监听器, 当前路径:', initialPath, '播放列表长度:', playList.length);
    
    // 获取视频ID和初始URL中的索引
    const { videoId, episodeIndex: urlEpisodeIndex } = getVideoInfoFromPath(initialPath);
    
    // 如果没有有效的视频ID，不进行历史处理
    if (videoId === null) {
      console.log('无法从路径获取有效的视频ID');
      return;
    }
    
    // 确定实际应该播放的集数索引
    let actualEpisodeIndex = 0;
    
    // 1. 如果URL已经指定了集数索引，优先使用
    if (urlEpisodeIndex !== null && urlEpisodeIndex >= 0 && urlEpisodeIndex < playList.length) {
      actualEpisodeIndex = urlEpisodeIndex;
      console.log('使用URL中指定的集数索引:', actualEpisodeIndex);
    } 
    // 2. 否则尝试从localStorage获取历史记录
    else {
      const storedIndex = getEpisodeHistory(videoId);
      if (storedIndex !== null && storedIndex >= 0 && storedIndex < playList.length) {
        actualEpisodeIndex = storedIndex;
        console.log('从localStorage读取选集记录:', actualEpisodeIndex);
      } else {
        console.log('没有找到历史记录或本地记录无效，使用第一集');
      }
    }
    
    // 确保历史状态与实际播放的集数一致
    if (!historyInitialized.current) {
      // 检查当前路径是否包含了正确的集数索引
      const correctPath = actualEpisodeIndex === 0 && !urlEpisodeIndex
        ? initialPath // 如果是第一集且URL没有指定索引，保持当前路径
        : `/detail/${videoId}-${actualEpisodeIndex}.html`; // 否则确保路径包含正确的集数索引
      
      // 如果路径需要调整，更新历史状态
      if (correctPath !== initialPath) {
        console.log('更新历史状态以匹配实际播放集数:', actualEpisodeIndex, '路径:', correctPath);
        window.history.replaceState({ 
          isInitialDetailPage: true,
          path: correctPath,
          videoId,
          episodeIndex: actualEpisodeIndex
        }, '', correctPath);
      } else {
        // 即使路径不变，也确保有状态对象
        window.history.replaceState({ 
          isInitialDetailPage: true,
          path: initialPath,
          videoId,
          episodeIndex: actualEpisodeIndex
        }, '', initialPath);
      }
      
      historyInitialized.current = true;
    }
    
    // 从URL路径中提取视频信息
    function getVideoInfoFromPath(path: string): { videoId: number | null; episodeIndex: number | null } {
      if (!path.includes('/detail/')) {
        return { videoId: null, episodeIndex: null };
      }
      
      const pathParts = path.split('/');
      let lastPart = pathParts[pathParts.length - 1];
      
      // 移除可能的.html后缀
      if (lastPart.endsWith('.html')) {
        lastPart = lastPart.substring(0, lastPart.length - 5);
      }
      
      // 解析 videoId-episodeIndex 格式
      const parts = lastPart.split('-');
      const idPart = parts[0];
      const videoId = parseInt(idPart, 10);
      
      // 提取集数索引，如果没有则为null
      let episodeIndex = null;
      if (parts.length > 1 && parts[1]) {
        const epIndex = parseInt(parts[1], 10);
        if (!isNaN(epIndex)) {
          episodeIndex = epIndex;
        }
      }
      
      return {
        videoId: isNaN(videoId) ? null : videoId,
        episodeIndex
      };
    }
    
    // 处理浏览器前进后退按钮点击事件
    const handlePopState = (event: PopStateEvent) => {
      const currentPath = window.location.pathname;
      const state = event.state || {};
      
      console.log('浏览器历史导航:', { 
        currentPath, 
        state,
        playListLength: playList.length 
      });
      
      // 如果返回到非详情页或网站首页，不需要额外处理
      // 浏览器会自动加载对应页面
      if (!currentPath.includes('/detail/')) {
        console.log('导航到非详情页面:', currentPath);
        return;
      }
      
      // 从URL中提取视频信息
      const { videoId, episodeIndex } = getVideoInfoFromPath(currentPath);
      
      // 如果无法获取有效索引，使用状态中存储的索引或默认值
      const targetIndex = episodeIndex !== null 
        ? episodeIndex 
        : (state.episodeIndex || 0);
        
      console.log('导航到集数:', targetIndex);
      
      // 验证索引在有效范围内
      if (targetIndex >= 0 && targetIndex < playList.length) {
        const episode = playList[targetIndex];
        if (episode) {
          console.log('历史记录导航切换到选集:', episode.name, '索引:', targetIndex);
          
          // 创建事件详情
          const eventDetail = { 
            url: episode.url, 
            name: episode.name,
            index: targetIndex
          };
          
          try {
            // 直接使用事件API派发事件
            const switchEvent = new CustomEvent('switchEpisode', { 
              detail: eventDetail,
              bubbles: true,
              cancelable: true
            });
            const dispatched = window.dispatchEvent(switchEvent);
            console.log('switchEpisode事件派发状态:', dispatched);
            
            // 派发 episodeChanged 事件，确保选集按钮状态更新
            const changedEvent = new CustomEvent('episodeChanged', {
              detail: eventDetail,
              bubbles: true,
              cancelable: true
            });
            window.dispatchEvent(changedEvent);
          } catch (error) {
            console.error('派发选集切换事件失败:', error);
          }
        } else {
          console.error('播放列表索引无效:', targetIndex);
        }
      } else {
        console.error('选集索引超出范围:', targetIndex, '播放列表长度:', playList.length);
      }
    };

    console.log('注册历史监听器, 播放列表长度:', playList.length);
    
    // 添加popstate事件监听
    window.addEventListener('popstate', handlePopState);
    
    // 组件卸载时移除监听
    return () => {
      window.removeEventListener('popstate', handlePopState);
    };
  }, [playList]);

  // 这是一个无UI组件，不需要渲染任何内容
  return null;
} 